var util = require('../../../utils/util.js');

Page({
  data: {
    tabs: [{
      name: "未使用"
    }, {
      name: "已使用"
    }, {
      name: "已过期"
    }],
    currentTab: 0,
    scrollTop: 0,
    //如果tabs数据是请求返回，则动态生成tabs数据
    couponList: [{
      loading: false,
      pullUpOn: true,
      pageIndex: 1,
      noData: false, //如果使用自定义无数据提示，则使用
      data: []
    }, {
      loading: false,
      pullUpOn: true,
      pageIndex: 1,
      noData: false,
      data: []
    }, {
      loading: false,
      pullUpOn: true,
      pageIndex: 1,
      noData: false,
      data: []
    }]
  },
  change(e) {
    this.setData({
      currentTab: e.detail.index
    })
    if (this.data.couponList[this.data.currentTab].pageIndex == 1) {
      this.getCouponList(this.data.currentTab)
    }
  },
  goIndex() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  couponCenter() {
    wx.navigateTo({
      url: '/pages/shopping/couponCenter/couponCenter',
    })
  },
  getCouponList(index) {
    let that = this;
    let list = [{
      loading: false,
      pullUpOn: true,
      pageIndex: 1,
      noData: false, //如果使用自定义无数据提示，则使用
      data: []
    }, {
      loading: false,
      pullUpOn: true,
      pageIndex: 1,
      noData: false,
      data: []
    }, {
      loading: false,
      pullUpOn: true,
      pageIndex: 1,
      noData: false,
      data: []
    }];
    util.request('coupon/list', {
      status: index
    }).then(function (res) {
      if (res.code === 0) {
        list.map(function (item, i) {
          if (index == i) {
            item.data = Object.assign(res.data);
          }
        })
        that.setData({
          couponList: list
        });
      }
    });
  },
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },
  onReachBottom() {
    let index = this.data.currentTab
    if (!this.data.couponList[index].pullUpOn) return;
    this.getCouponList(index)
  },
  onLoad: function (options) {
    this.getCouponList(this.data.currentTab)
  },
  // 下拉刷新
  onPullDownRefresh: function () {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    var that = this;

    that.getCouponList(this.data.currentTab);
    let index = this.data.currentTab
    this.getCouponList(index)
    // 隐藏导航栏加载框
    wx.hideNavigationBarLoading();
    // 停止下拉动作
    wx.stopPullDownRefresh();
  },
  onShow: function () {
    this.getCouponList(this.data.currentTab)
  },
  onUnload: function () {
    // 页面关闭
  }
})